﻿using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Security;
using System.Collections.Generic;
using System.Xml;
using System.Reflection;
using Microsoft.SharePoint.Utilities;

namespace Hutchinson.CustomField.LookupField
{
    public enum VisualTemplateType
    {
        HutLookupField = 1,
        RadioHutLookupField = 2,
        MultipleHutLookupField = 3,
        CheckBoxHutLookupField = 4
    }

    // TODO: Replace, as needed, "SPFieldText" with some other class derived from SPField. 
    // TODO: Update, as needed, ParentType element in fldtypes*.xml in this solution. 
    [CLSCompliant(false)]
    [Guid("f7ed522f-ec6e-47c3-bbd9-efb113b11a8f")]
    public class HutLookupFieldField : SPFieldLookup
    {
        // Propriétés sous forme de chaines de caractères
        // Initialisées à null afin de limiter les appels à GetFieldAttributeValue()
        string _lookupFieldParametred = null;
        string _repeatDirection = null;
        string _strVisualTemplateType = null;
        string _strNombreColonnes = null;

        // Propriétés sous forme d'objets typés (plus faciles à utiliser)
        VisualTemplateType _VisualTemplateType;
        int _nombreColonnes;

        public HutLookupFieldField(SPFieldCollection fields, string fieldName)
            : base(fields, fieldName)
        {
            Init();
        }

        public HutLookupFieldField(SPFieldCollection fields, string typeName, string displayName)
            : base(fields, typeName, displayName)
        {
            Init();
        }

        public override BaseFieldControl FieldRenderingControl
        {
            [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
            get
            {
                BaseFieldControl fieldControl = null;

                switch (this.ShowType)
                {
                    case VisualTemplateType.MultipleHutLookupField:
                        fieldControl = new HutLookupFieldControlMulti();
                        break;
                    case VisualTemplateType.CheckBoxHutLookupField:
                        fieldControl = new HutLookupFieldControlCheckbox();
                        break;
                    case VisualTemplateType.RadioHutLookupField:
                        fieldControl = new HutLookupFieldControlRadio();
                        break;
                    default:
                        fieldControl = new HutLookupFieldControl();
                        break;
                }

                fieldControl.FieldName = this.InternalName;

                return fieldControl;
            }
        }

        public void SetFieldAttributeValue(string property, object value)
        {
            Type t = typeof(HutLookupFieldField);
            MethodInfo mi = t.GetMethod("SetFieldAttributeValue", BindingFlags.Instance | BindingFlags.NonPublic);
            object ret = mi.Invoke(this, new object[] { property, value });
        }

        public string GetFieldAttributeValue(string property)
        {
            XmlDocument document = new XmlDocument();
            document.LoadXml(this.SchemaXml);
            XmlElement documentElement = document.DocumentElement;
            if (documentElement.Attributes[property] != null)
                return documentElement.Attributes[property].Value;
            else
                return null;
        }

        public override bool AllowMultipleValues
        {
            get
            {
                return base.AllowMultipleValues;
            }
            set
            {
                if (value)
                {
                    SetFieldAttributeValue("Mult", "TRUE");
                    SetFieldAttributeValue("Sortable", "FALSE");
                }
                else
                {
                    SetFieldAttributeValue("Mult", "FALSE");
                    SetFieldAttributeValue("Sortable", "TRUE");
                }
            }
        }

        public string RepeatDirection
        {
            get
            {
                if (_repeatDirection == null)
                    _repeatDirection = GetFieldAttributeValue("RepeatDirection");

                return _repeatDirection;
            }
            set
            {
                _repeatDirection = value;
                SetFieldAttributeValue("RepeatDirection", _repeatDirection);
            }
        }

        public int NombreColonnes
        {
            get
            {
                if (_strNombreColonnes == null)
                {
                    _strNombreColonnes = GetFieldAttributeValue("NombreColonnes");
                    if (_strNombreColonnes == null)
                        _strNombreColonnes = "1";

                    _nombreColonnes = int.Parse(_strNombreColonnes);
                }
                return _nombreColonnes;
            }
            set
            {
                _nombreColonnes = value;
                SetFieldAttributeValue("NombreColonnes", _nombreColonnes.ToString());
            }
        }

        public string LookupFieldParametred
        {
            get
            {
                if (_lookupFieldParametred == null)
                    _lookupFieldParametred = GetFieldAttributeValue("LookupFieldParametred");

                return _lookupFieldParametred;
            }
            set
            {
                _lookupFieldParametred = value;
                SetFieldAttributeValue("LookupFieldParametred", _lookupFieldParametred);
            }
        }

        public VisualTemplateType ShowType
        {
            get
            {
                if (_strVisualTemplateType == null)
                {
                    _strVisualTemplateType = GetFieldAttributeValue("ShowType");
                    if (_strVisualTemplateType == null)
                        _strVisualTemplateType = VisualTemplateType.HutLookupField.ToString();

                    _VisualTemplateType = (VisualTemplateType)Enum.Parse(typeof(VisualTemplateType), _strVisualTemplateType);
                }
                return _VisualTemplateType;
            }
            set
            {
                _VisualTemplateType = value;
                SetFieldAttributeValue("ShowType", _VisualTemplateType.ToString());
            }
        }

        public void SetShowField(string value)
        {

            //SetFieldAttributeValue("ShowField", "Title");
            SetFieldAttributeValue("ShowField", value);
        }

        private void Init()
        {
            _lookupFieldParametred = this.LookupFieldParametred;
            _repeatDirection = this.RepeatDirection;
            _nombreColonnes = this.NombreColonnes;
            _VisualTemplateType = this.ShowType;
        }


        //public override string ToString()
        //{
        //    return cleanValue(base.ToString());
        //}

        /// <summary>
        /// Nettoyage des valeurs et suppression des caractères inutiles
        /// </summary>
        /// <param name="item">Elément à nettoyer</param>
        /// <returns></returns>
        internal static string cleanValue(string item)
        {
            if (item.Contains(";#"))
                return item.Split("#".ToCharArray())[1];
            else
                return item.Trim();
        }

        internal string GetRessources(string Key)
        {
            string name = "Hutchinson.CustomField.LookupField";
            string head = string.Format("$Resources:{0},{1}", name, Key);
            string mess = SPUtility.GetLocalizedString(head, name, SPContext.Current.Web.Language);
            return mess;
        }
    }
}
